<?php

namespace App\Models\video;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use Illuminate\Support\Facades\Cache;

class WxServer
{
    protected $appId;
    protected $appSecret;
    private $returnData;
    static $object;

    public function __construct($appId, $appSecret)
    {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
        $this->returnData = ErrorCode::code("success");
    }

    /**
     * @throws \Exception
     * @return WxServer
     */
    public static function getInstance(){
        $param = func_get_args();
        if(empty($param)){
            static $settingData;
            if(empty($settingData))
                $settingData = VideoSettingModel::getFields("app_id,app_secret", ["mall_id" => request()->mallData["id"]], true, false);
            if(empty($settingData["appId"]) || empty($settingData["appSecret"])){
                throw new \Exception("小程序未配置");
            }
            $param[0] = $settingData["appId"];
            $param[1] = $settingData["appSecret"];
        }
        $md5 = md5(implode("", $param));
        if(empty(self::$object[$md5])){
            self::$object[$md5] = new self($param[0], $param[1]);
        }
        return self::$object[$md5];
    }

    public function delQrCode(){
        $save_file = md5($this->appId . $this->appSecret);
        return true;
    }

    // 生成二维码
    public function generateWxCode($params, $pagePath){
        $access_token = $this->getToken();
        if (isset($access_token["code"])) {
            return $access_token;
        }
        $data = ['scene' => $params];
        if(!empty($pagePath)){
            $data["page"] = $pagePath;
        }
        $result = UpTools::curl("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={$access_token}", json_encode($data, JSON_UNESCAPED_SLASHES));
        $response = json_decode($result, true);
        if (empty($response['errcode'])) {
            return $result;
        } else {
            UpTools::writeLog("生成二维码出错：码-$response[errcode]；消息-$response[errmsg]", "wxServer/generateQrCode.txt");
            $this->returnData["code"] = $response["errcode"];
            $this->returnData["msg"] = $response["errmsg"];
        }
        return $this->returnData;
    }

    /**
     * @param string $code
     * @return mixed
     * 通过code获取accessToken信息
     */
    public function getAccessToken($code)
    {
        $requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
        $accessTokenRes = json_decode(UpTools::curl($requestUrl), true);
        if(!isset($accessTokenRes["access_token"])){
            return false;
        }else{
            return $accessTokenRes;
        }
    }

    /**
     * @param string $access_token
     * @param string $openid
     * @return mixed
     * 获取微信用户信息
     */
    public function getWxUserInfo($access_token, $openid)
    {
        $wxUserData = json_decode(UpTools::curl("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}"), true);
        if(empty($wxUserData["openid"])){
            return false;
        }else{
            return $wxUserData;
        }
    }

    /**
     * @return mixed
     * 获取token信息
     */
    public function getToken()
    {
        $this->returnData = ErrorCode::code("success");
        if ($access_token = Cache::get($this->appId . "_token")) {
            return $access_token;
        }
        $response = UpTools::curl("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}");
        $result = json_decode($response, true);
        if (isset($result['errcode']) && $result['errcode'] != 0) {
            UpTools::writeLog("getToken：".var_export($result,true), "wxServer/getToken.txt");
            $this->returnData["code"] = $result['errcode'];
            $this->returnData["msg"] = $result["errmsg"];
            return $this->returnData;
        } else {
            Cache::put($this->appId."_token", $result['access_token'], $result['expires_in'] / 60);
            return $result['access_token'];
        }
    }

    /**
     * @param $openid
     * @param $template_id
     * @param array $postData
     * @param string $page
     * @param string $color
     * @return bool|mixed|string
     * 小程序发送微信模板消息接口
     */
    public function sendTplNotice($openid, $template_id, $postData = [], $page = 'pages/index/index')
    {
        $token = $this->getToken();
        if (isset($token["code"])) {
            return $token;
        }

        $data = [
            'touser' => $openid,
            'template_id' => $template_id,
            'page' => $page,
            'data' => $postData
        ];

        $result = UpTools::curl("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$token}", json_encode($data));
        $result = json_decode($result, true);
        if($result['errcode'] !== 0){
            UpTools::writeLog("sendTplNotice：发送模板消息出错：错误码：$result[errcode]；错误消息：$result[errmsg]；".var_export($data, true), "wxTemplate.txt");
            return false;
        }
        return $result;
    }
}